package net.kem.android.positioner;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

/**
 * This example taken from
 * http://www.codeproject.com/Articles/112044/positioner-
 * App-to-Find-Current-Nearest-Location-us
 *
 * @author Evgeny.Kurtser
 *
 */
public class SettingsGPSActivity extends Activity {
	private EditText editGPSRefreshInterval;
	private EditText editGPSRefreshDistance;
	private EditText editPOIRadius;
	private EditText editGPSAccuracyThreshold;
	private CheckBox cbGPSAutoRefreshDistance;

	private Button buSave;
	private Button buCancel;

	private String lastGPSRefreshInterval;
	private String lastGPSRefreshDistance;

	private PositionerService.LocalBinder binder;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings_gps);

		Settings.init(this);

		editGPSRefreshInterval = (EditText) findViewById(R.id.settingsGPSRefreshInterval);
		editGPSRefreshDistance = (EditText) findViewById(R.id.settingsGPSRefreshDistance);
		cbGPSAutoRefreshDistance = (CheckBox) findViewById(R.id.settingsAutoGPSRefreshDistance);
		editPOIRadius = (EditText) findViewById(R.id.settingsPOIRadius);
		editGPSAccuracyThreshold = (EditText) findViewById(R.id.settingsGPSAccuracyThreshold);
		buSave = (Button) findViewById(R.id.settingsButtonSave);
		buCancel = (Button) findViewById(R.id.settingsButtonCancel);

		// Restore preferences
		editGPSRefreshInterval.setText(String.valueOf(Settings.getGPSRefreshInterval()));
		editGPSRefreshDistance.setText(String.valueOf(Settings.getGPSRefreshDistance()));
		cbGPSAutoRefreshDistance.setChecked(Settings.getGPSAutoRefreshDistance());
		editPOIRadius.setText(String.valueOf(Settings.getPOIRadius()));
		editGPSAccuracyThreshold.setText(String.valueOf(Settings.getGPSAccuracyThreshold()));

		// Disable editGPSRefreshDistance if cbGPSAutoRefreshDistance is active.
		editGPSRefreshDistance.setEnabled(!cbGPSAutoRefreshDistance.isChecked());

//		Editor e = this.getPreferences(Context.MODE_PRIVATE).edit();
//		e.putString("password", mPassword);
//		e.commit();

		editGPSRefreshInterval.addTextChangedListener(new TextWatcher() {
			@Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
			@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				if(lastGPSRefreshInterval == null) {
					lastGPSRefreshInterval = s.toString();
				}
			}
			@Override public void afterTextChanged(Editable s) {
				if(s.toString().length() == 0) {
					String errorMsg = getString(R.string.errorCannotBeEmpty);
					editGPSRefreshInterval.setError(errorMsg);
					buSave.setEnabled(false);
				} else {
					buSave.setEnabled(true);
				}
			}
		});
		editGPSRefreshDistance.addTextChangedListener(new TextWatcher() {
			@Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
			@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				if(lastGPSRefreshDistance == null) {
					lastGPSRefreshDistance = s.toString();
				}
			}
			@Override public void afterTextChanged(Editable s) {
				if(s.toString().length() == 0) {
					String errorMsg = getString(R.string.errorCannotBeEmpty);
					editGPSRefreshDistance.setError(errorMsg);
					buSave.setEnabled(false);
				} else {
					buSave.setEnabled(true);
				}
			}
		});
		cbGPSAutoRefreshDistance.setOnCheckedChangeListener(new OnCheckedChangeListener()
		{
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				editGPSRefreshDistance.setEnabled(!isChecked);
				if (isChecked) {
					editGPSRefreshDistance.setText(String.valueOf(Settings.GPS_REFRESH_DISTANCE_DEFAULT));
				}
			}
		});
		editPOIRadius.addTextChangedListener(new TextWatcher() {
			@Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
			@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override public void afterTextChanged(Editable s) {
				if(s.toString().length() == 0) {
					String errorMsg = getString(R.string.errorCannotBeEmpty);
					editPOIRadius.setError(errorMsg);
					buSave.setEnabled(false);
				} else {
					buSave.setEnabled(true);
				}
			}
		});
		editGPSAccuracyThreshold.addTextChangedListener(new TextWatcher() {
			@Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
			@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override public void afterTextChanged(Editable s) {
				if(s.toString().length() == 0) {
					String errorMsg = getString(R.string.errorCannotBeEmpty);
					editGPSAccuracyThreshold.setError(errorMsg);
					buSave.setEnabled(false);
				} else {
					buSave.setEnabled(true);
				}
			}
		});

		buSave.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				// Save user preferences. We need an Editor object to make changes.
				Settings.setGPSAutoRefreshDistance(cbGPSAutoRefreshDistance.isChecked());
				Settings.setGPSRefreshInterval(Integer.parseInt(editGPSRefreshInterval.getText().toString()));
				Settings.setGPSRefreshDistance(Integer.parseInt(editGPSRefreshDistance.getText().toString()));
				Settings.setPOIRadius(Integer.parseInt(editPOIRadius.getText().toString()));
				Settings.setGPSAccuracyThreshold(Integer.parseInt(editGPSAccuracyThreshold.getText().toString()));

				Integer currentGPSRefreshInterval = Settings.getGPSRefreshInterval();
				if(lastGPSRefreshInterval != null) {
					Integer lastInterval = Integer.parseInt(lastGPSRefreshInterval);
					if(lastInterval != currentGPSRefreshInterval) {
						binder.setPeriodicalCalls();
					}
				}
				if(lastGPSRefreshDistance != null) {
					Integer lastDistance = Integer.parseInt(lastGPSRefreshDistance);
					Integer currentGPSRefreshDistance = Settings.getGPSRefreshDistance();
					if(lastDistance != currentGPSRefreshDistance) {
						binder.addLocationListener(null, currentGPSRefreshDistance, currentGPSRefreshInterval);
					}
				}
				setResult(RESULT_OK);
				finish();
			}
		});
		buCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				//SettingsActivity.this.setVisible(false);
				setResult(RESULT_CANCELED);
				finish();
			}
		});
	}

	@Override
	protected void onStart() {
		// The activity is about to become visible.
		super.onStart();
		// Bind to LocalService
		Intent intent = new Intent(this, PositionerService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onStop() {
		// The activity is no longer visible (it is now "stopped")
		super.onStop();
		// Unbind from the service
		if (binder != null) {
			unbindService(mConnection);
		}
	}

	/** Defines callbacks for service binding, passed to bindService() */
	private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			// We've bound to LocalService, cast the IBinder and get LocalService instance
			binder = (PositionerService.LocalBinder) service;
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			binder = null;
		}
	};
}